<template>
  <div class="ocr-container">
    <div class="btn-animate btn-animate__surround" @click="goToHome">
      <span>🏠点击返回主页面</span>
    </div>
    
    <div class="header">
      <h1>📃OCR文字识别</h1>
      <p>智能识别图片中的文字内容，支持多种语言和格式</p>
    </div>

    <div class="main-content">
      <!-- 上传区域 -->
      <div class="upload-section">
        <el-upload
          class="upload-area"
          drag
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          accept="image/*"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            🧩将图片拖到此处，或<em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            支持 JPG、PNG、BMP 等格式，单张图片不超过10MB
          </div>
        </el-upload>
      </div>

      <!-- 图片预览和识别结果 -->
      <div class="result-section" v-if="imageUrl">
        <div class="image-preview">
          <h3>图片预览</h3>
          <img :src="imageUrl" alt="待识别图片" class="preview-image" />
        </div>

        <div class="recognition-controls">
          <el-button type="primary" size="large" @click="startRecognition" :loading="isRecognizing" 
            :disabled="!imageFile" class="recognize-btn">
            <i class="el-icon-search"></i>
            {{ isRecognizing ? '识别中...' : '开始识别' }}
          </el-button>

          <el-button
            v-if="ocrResult" type="success" size="large" @click="copyText" class="copy-btn">
            <i class="el-icon-document-copy"></i>
            复制文字
          </el-button>

          <el-button
            v-if="ocrResult" type="info" size="large" @click="downloadText" class="download-btn">
            <i class="el-icon-download"></i>
            ⬇️下载文本
          </el-button>
        </div>

        <!-- 识别结果 -->
        <div class="result-display" v-if="ocrResult">
          <h3>识别结果</h3>
          <div class="result-stats">
            <el-tag type="success">识别文字: {{ ocrResult.total_texts }} 处</el-tag>
            <el-tag type="info">处理时间: {{ ocrResult.process_time }} 秒</el-tag>
          </div>
          
          <el-input
            v-model="ocrResult.full_text"
            type="textarea"
            :rows="10"
            readonly
            class="result-textarea"
            placeholder="识别结果将显示在这里..."
          />

          <!-- 详细结果表格 -->
          <div class="detailed-results" v-if="ocrResult.details && ocrResult.details.length > 0">
            <h4>详细识别结果</h4>
            <el-table :data="ocrResult.details" style="width: 100%">
              <el-table-column prop="text" label="识别文字" min-width="200" />
              <el-table-column prop="confidence" label="置信度" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.confidence > 0.9 ? 'success' : row.confidence > 0.7 ? 'warning' : 'danger'">
                    {{ (row.confidence * 100).toFixed(1) }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="position" label="位置" width="150">
                <template #default="{ row }">
                  [{{ row.bbox.x1 }}, {{ row.bbox.y1 }}] - [{{ row.bbox.x2 }}, {{ row.bbox.y2 }}]
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 提示信息 -->
      <el-alert
        v-if="message"
        :title="message.text"
        :type="message.type"
        :closable="false"
        class="message-alert"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 数据
const imageFile = ref(null);
const imageUrl = ref('');
const isRecognizing = ref(false);
const ocrResult = ref(null);
const message = ref(null);

// 处理文件选择
const handleFileChange = (file) => {
  if (file.raw) {
    imageFile.value = file.raw;
    imageUrl.value = URL.createObjectURL(file.raw);
    ocrResult.value = null; // 清空之前的结果
  }
};

// 开始OCR识别
const startRecognition = async () => {
  if (!imageFile.value) {
    ElMessage.warning('请先选择图片');
    return;
  }

  isRecognizing.value = true;
  message.value = null;
  ocrResult.value = null;

  try {
    const startTime = Date.now();
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('image', imageFile.value);

    // 调用OCR API
    const response = await fetch('http://localhost:5000/api/ocr-recognition', {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      throw new Error('识别失败');
    }

    const result = await response.json();
    
    if (result.success) {
      const processTime = ((Date.now() - startTime) / 1000).toFixed(2);
      
      // 构建识别结果
      ocrResult.value = {
        full_text: result.data.map(item => item.text).join('\n'),
        total_texts: result.total_texts,
        process_time: processTime,
        details: result.data.map(item => ({
          text: item.text,
          confidence: item.confidence,
          bbox: item.bbox,
          position: `[${item.bbox.x1}, ${item.bbox.y1}] - [${item.bbox.x2}, ${item.bbox.y2}]`
        }))
      };

      ElMessage.success(`识别完成，共找到 ${result.total_texts} 处文字`);
    } else {
      throw new Error(result.error || '识别失败');
    }

  } catch (error) {
    console.error('OCR识别错误:', error);
    ElMessage.error(error.message || '识别失败，请重试');
  } finally {
    isRecognizing.value = false;
  }
};

// 复制识别结果
const copyText = () => {
  if (ocrResult.value && ocrResult.value.full_text) {
    navigator.clipboard.writeText(ocrResult.value.full_text).then(() => {
      ElMessage.success('文字已复制到剪贴板');
    }).catch(() => {
      ElMessage.error('复制失败，请手动复制');
    });
  }
};

// 下载识别结果
const downloadText = () => {
  if (ocrResult.value && ocrResult.value.full_text) {
    const blob = new Blob([ocrResult.value.full_text], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `ocr_result_${new Date().getTime()}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    ElMessage.success('文本已下载');
  }
};

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 清理
onMounted(() => {
  // 清理可能存在的对象URL
  return () => {
    if (imageUrl.value) {
      URL.revokeObjectURL(imageUrl.value);
    }
  };
});
</script>

<style scoped>
@import '../assets/Ocr.css'
</style>
